<?php

namespace app\api\model\kuyou\applet;

use app\api\controller\kuyou\applet\Commons;
use think\Model;
use think\Db;
use Exception;
class Adjustment extends Model
{

    // 表名
    protected $name = 'kuyou_adjustment';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit,$sort_field,$sort_type){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        if($pageStatus){
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order($sort_field,$sort_type)->page($page,$limit)->field("id,purchase_code,business_type,money,preparation_id,remark,print_num,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time")->select())->toArray();
        }else{
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order($sort_field,$sort_type)->field("id,purchase_code,business_type,money,preparation_id,remark,print_num,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time")->select())->toArray();
        }
        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['preparation_name'] = Db::name('admin')->where(['id'=>$list_v['preparation_id']])->value('username');
        }
        $count = self::where(function ($query) use ($where) {
            $query->where($where);
        })->count();

        foreach ($list as $k=>$v){
            $list[$k]['info_list'] = Db::name('kuyou_adjustment_info')->alias('a')
                ->join('kuyou_goods g','g.id=a.goods_id')
                ->where(['a.purchase_code'=>$v['purchase_code']])
                ->field('a.goods_id,a.goods_unit,a.money,a.stores_id,a.remark,g.goods_code,g.goods_name,g.goods_image')->select();
        }

        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 获取详情
     * @param string $purchase_code
     * @return array
     */
    public static function getDetail($purchase_code){
        $detail = self::where(function ($query) use ($purchase_code) {
            $query->where('purchase_code', '=', $purchase_code);
        })->field("id,purchase_code,business_type,money,preparation_id,remark,print_num,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time")->find();
        if($detail){
            $detail['info_list'] = Db::name('kuyou_adjustment_info')->alias('a')
                ->join('kuyou_goods g','g.id=a.goods_id')
                ->where(['a.purchase_code'=>$detail['purchase_code']])
                ->field('a.purchase_code,FROM_UNIXTIME(a.purchase_time,\'%Y-%m-%d\') as purchase_time,a.goods_id,a.goods_unit,a.money,a.stores_id,a.remark,g.goods_code,g.goods_name,g.goods_image')->select();
        }else{
            return ['status'=>500,'msg'=>'未查询到相关数据'];
        }
        return ['status'=>200,'msg'=>$detail];
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'purchase_code|单据编号'=>'require',
                'purchase_time|单据时间'=>'require',
                'info_list|详细信息'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $status = (new Commons())->checkCode($detail['purchase_code'],14);//验证编号是否合法
                if($status){
                    $adminId = (new Commons())->getAdminId();
                    if(empty($adminId)){
                        return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
                    }
                    $info_list = (array)json_decode($detail['info_list'], true);

                    $data = [];
                    $price = 0;
                    $goods_stock_log = [];
                    foreach ($info_list as $k=>$v){
                        if(!empty($v['goods_id'])){//有产品ID
                            $price+=$v['money'];
                            if(!isset($v['money']) || empty($v['money'])){
                                return ['status'=>500,'msg'=>'请输入调整价格'];
                            }else if(!isset($v['goods_unit']) || empty($v['goods_unit'])){
                                return ['status'=>500,'msg'=>'请选择单位'];
                            }else if(!isset($v['stores_id']) || empty($v['stores_id'])){
                                return ['status'=>500,'msg'=>'请选择仓库'];
                            }
                            $goods = Db::name('kuyou_goods')->where(['id'=>$v['goods_id']])->find();
                            if(empty($goods)){
                                return ['status'=>500,'msg'=>'商品不存在'];
                            }
                            $stores = Db::name('kuyou_stores')->where(['id'=>$v['stores_id']])->find();
                            if(empty($stores)){
                                return ['status'=>500,'msg'=>'仓库不存在'];
                            }

                            $data[] = [
                                'purchase_code'     =>  $detail['purchase_code'],
                                'purchase_time'     =>  strtotime($detail['purchase_time']),
                                'goods_id'          =>  $v['goods_id'],//商品信息
                                'goods_unit'        =>  (int)$v['goods_unit'],
                                'stores_id'         =>  (int)$v['stores_id'],
                                'money'             =>  (float)$v['money'],
                                'remark'            =>  $v['remark'],
                                'createtime'        => time(),
                                'updatetime'        => time(),
                            ];

                            $goods_stock_log[] = [
                                'purchase_code' => $detail['purchase_code'],
                                'purchase_id'   => '',
                                'purchase_time' => strtotime($detail['purchase_time']),
                                'business_type' => '7',
                                'goods_id'      => $v['goods_id'],
                                'goods_code'    => $goods['goods_code'],
                                'goods_unit'    => (float)$v['goods_unit'],
                                'stores_id'     => (float)$v['stores_id'],
                                'remark'        => $v['remark'],
                                'enter_cost'    => (float)$v['money'],
                                'createtime'    => time(),
                                'updatetime'    => time(),
                            ];
                        }
                    }
                    if(!empty($data)){
                        $rowdata = [
                            'purchase_code'     =>  $detail['purchase_code'],
                            'purchase_time'     =>  strtotime($detail['purchase_time']),
                            'business_type'     =>  '1',
                            'money'             =>  $price,
                            'preparation_id'    =>  $adminId,
                            'remark'            =>  $detail['remark'],
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ];
                    }

                    $model = new Adjustment();
                    $row = $model->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                    if($row){
                        return ['status'=>500,'msg'=>'编号已存在'];
                    }
                    $result = false;
                    Db::startTrans();
                    try {
                        $model->allowField(true)->save($rowdata);
                        $result = $model->id;
                        if(isset($goods_stock_log) && !empty($goods_stock_log)){
                            foreach ($goods_stock_log as $goods_stock_log_k=>$goods_stock_log_v){
                                $goods_stock_log[$goods_stock_log_k]['purchase_id'] = $result;
                            }
                            Db::name('kuyou_goods_log')->insertAll($goods_stock_log);
                        }
                        Db::name('kuyou_adjustment_info')->where(['purchase_code'=>$detail['purchase_code']])->delete();
                        Db::name('kuyou_adjustment_info')->insertAll($data);
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        return ['status'=>500,'msg'=>$e->getMessage()];
                    }
                    if($result){
                        return ['status'=>200,'msg'=>$detail['purchase_code']];
                    }else{
                        return ['status'=>500,'msg'=>'添加失败'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 更新
     * @param array $detail
     * @return array
     */
    public static function editDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'old_purchase_code|原单据编号'=>'require',
                'purchase_code|单据编号'=>'require',
                'purchase_time|单据时间'=>'require',
                'info_list|详细信息'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $adminId = (new Commons())->getAdminId();
                if(empty($adminId)){
                    return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
                }
                $status = (new Commons())->checkCode($detail['purchase_code'],14);//验证编号是否合法
                if($status){
                    $model = new Adjustment();
                    $row = $model->where(['purchase_code'=>$detail['old_purchase_code']])->find();
                    if(empty($row)){
                        return ['status'=>500,'msg'=>'修改的单据不存在'];
                    }
                    $info_list = (array)json_decode($detail['info_list'], true);
                    $info_id = Db::name('kuyou_adjustment_info')->where(['purchase_code'=>$detail['old_purchase_code']])->column('id');

                    $data = [];
                    $price = 0;
                    $goods_stock_log = [];
                    foreach ($info_list as $k=>$v){
                        if(!empty($v['goods_id'])){//有产品ID
                            $price+=$v['money'];
                            if(!isset($v['money']) || empty($v['money'])){
                                return ['status'=>500,'msg'=>'请输入调整价格'];
                            }else if(!isset($v['goods_unit']) || empty($v['goods_unit'])){
                                return ['status'=>500,'msg'=>'请选择单位'];
                            }else if(!isset($v['stores_id']) || empty($v['stores_id'])){
                                return ['status'=>500,'msg'=>'请选择仓库'];
                            }
                            $goods = Db::name('kuyou_goods')->where(['id'=>$v['goods_id']])->find();
                            if(empty($goods)){
                                return ['status'=>500,'msg'=>'商品不存在'];
                            }
                            $stores = Db::name('kuyou_stores')->where(['id'=>$v['stores_id']])->find();
                            if(empty($stores)){
                                return ['status'=>500,'msg'=>'仓库不存在'];
                            }

                            $data[] = [
                                'purchase_code'     =>  $detail['purchase_code'],
                                'purchase_time'     =>  strtotime($detail['purchase_time']),
                                'goods_id'          =>  $v['goods_id'],//商品信息
                                'goods_unit'        =>  (int)$v['goods_unit'],
                                'stores_id'         =>  (int)$v['stores_id'],
                                'money'             =>  (float)$v['money'],
                                'remark'            =>  $v['remark'],
                                'createtime'        => time(),
                                'updatetime'        => time(),
                            ];

                            $goods_stock_log[] = [
                                'purchase_code' => $detail['purchase_code'],
                                'purchase_id'   => '',
                                'purchase_time' => strtotime($detail['purchase_time']),
                                'business_type' => '7',
                                'goods_id'      => $v['goods_id'],
                                'goods_code'    => $goods['goods_code'],
                                'goods_unit'    => (float)$v['goods_unit'],
                                'stores_id'     => (float)$v['stores_id'],
                                'remark'        => $v['remark'],
                                'enter_cost'    => (float)$v['money'],
                                'createtime'    => time(),
                                'updatetime'    => time(),
                            ];
                        }
                    }
                    if(!empty($data)){
                        $rowdata = [
                            'purchase_code'     =>  $detail['purchase_code'],
                            'purchase_time'     =>  strtotime($detail['purchase_time']),
                            'business_type'     =>  '1',
                            'money'             =>  $price,
                            'preparation_id'    =>  $adminId,
                            'remark'            =>  $detail['remark'],
                        ];
                    }

                    if($detail['purchase_code']!=$detail['old_purchase_code']){
                        $purchase_id = $model->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                        if($purchase_id){
                            return ['status'=>500,'msg'=>'单据编号已使用，请重新输入单据编号'];
                        }
                    }

                    if($row){
                        $res = false;
                        Db::startTrans();
                        try {
                            $rowdata['updatetime'] = time();
                            $res = $model->where(['purchase_code'=>$detail['old_purchase_code']])->update($rowdata);
                            Db::name('kuyou_adjustment_info')->where(['id'=>['in',$info_id]])->delete();
                            Db::name('kuyou_goods_log')->where(['business_type'=>'7','purchase_id'=>['in',$info_id]])->delete();

                            if($goods_stock_log){
                                foreach ($goods_stock_log as $goods_stock_log_k=>$goods_stock_log_v){
                                    $goods_stock_log[$goods_stock_log_k]['purchase_id'] = $row['id'];
                                }
                                Db::name('kuyou_goods_log')->insertAll($goods_stock_log);
                            }
                            Db::name('kuyou_adjustment_info')->insertAll($data);
                            Db::commit();
                        } catch (Exception $e) {
                            Db::rollback();
                            return ['status'=>500,'msg'=>$e->getMessage()];
                        }
                        if($res){
                            return ['status'=>200,'msg'=>'更新成功'];
                        }else{
                            return ['status'=>500,'msg'=>'更新失败'];
                        }
                    }else{
                        return ['status'=>500,'msg'=>'未查询到可更新数据'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 删除
     * @param string $purchase_code
     * @return array
     */
    public static function delDetail($purchase_code){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $purchase_code = explode(',',$purchase_code);
            $model = new Adjustment();
            $list = $model->where(['purchase_code'=>['in',$purchase_code]])->select();

            $count = 0;
            $res = false;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $res = $model->where(['purchase_code'=>$v['purchase_code']])->delete();
                    $count += $res;
                    Db::name('kuyou_adjustment_info')->where(['purchase_code'=>$v['purchase_code']])->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }
            if($res){
                return ['status'=>200,'msg'=>$count];
            }else{
                return ['status'=>500,'msg'=>'删除失败'];
            }
        }
    }

}
